package com.rtp.transformer.fin.client;

import java.util.Iterator;
import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.SourcesTableEvents;
import com.google.gwt.user.client.ui.TableListener;
import com.google.gwt.user.client.ui.Widget;
import com.rtp.transformer.fin.client.model.AccountCategory;
import com.rtp.transformer.fin.client.model.GLItem;
 

public class GLFlexTable extends Composite implements TableListener,
		ClickListener {

	private static final int VISIBLE_EMAIL_COUNT = 20;

	private HTML countLabel = new HTML();
	private HTML newerButton = new HTML(
			"<a href='javascript:;'>&lt; newer</a>", true);
	private HTML olderButton = new HTML(
			"<a href='javascript:;'>older &gt;</a>", true);
	
	
	final HorizontalPanel panel = new HorizontalPanel();
	private int startIndex, selectedRow = -1;
	final FlexTable table = new FlexTable();
	private int count;
	private List list;
	private HorizontalPanel navBar = new HorizontalPanel();
	private FinServiceAsync service = FinService.Util.getInstance();

	public GLFlexTable() {

		initWidget(panel);

		panel.add(table);
		table.addTableListener(this);
		newerButton.addClickListener(this);
		olderButton.addClickListener(this);

		// Create the 'navigation' bar at the upper-right.
		HorizontalPanel innerNavBar = new HorizontalPanel();
		navBar.setStyleName("mail-ListNavBar");
		innerNavBar.add(newerButton);
		innerNavBar.add(countLabel);
		innerNavBar.add(olderButton);

		navBar
				.setHorizontalAlignment(com.google.gwt.user.client.ui.HorizontalPanel.ALIGN_RIGHT);
		navBar.add(innerNavBar);
		navBar.setWidth("100%");
		initTable();
//		update();
	}

	public void onCellClicked(SourcesTableEvents sender, int row, int cell) {
		// TODO Auto-generated method stub
		if (row > 0) {
			selectRow(row - 1);
	      AccountCategory ac = (AccountCategory) list.get(row-2);
		  MyPopup p = new MyPopup(ac);
	      int left = ((Widget)sender).getAbsoluteLeft() + 10;
	      int top = ((Widget)sender).getAbsoluteTop() + 10;
	      p.setPopupPosition(left,top);
	      p.show();
		}
	}

	public void onClick(Widget sender) {
		if (sender == olderButton) {
			// Move forward a page.
			startIndex += VISIBLE_EMAIL_COUNT;
			if (startIndex >= count) {
				startIndex -= VISIBLE_EMAIL_COUNT;
			} else {
				styleRow(selectedRow, false);
				selectedRow = -1;
				update();
			}
		} else if (sender == newerButton) {
			// Move back a page.
			startIndex -= VISIBLE_EMAIL_COUNT;
			if (startIndex < 0) {
				startIndex = 0;
			} else {
				styleRow(selectedRow, false);
				selectedRow = -1;
				update();
			}
		}
	}

	private void initTable() {
		// Create the header row.
		
		table.setWidth("80%");
		table.setText(0, 0, "Category");
		table.setText(0, 1, "Name");
		table.setText(0, 2, "Balance");
		table.setText(0, 3, "debitTotal");
		table.setText(0, 4, "creditTotal");

		table.getCellFormatter().setWidth(0, 0, "15%");
		table.getCellFormatter().setWidth(0, 1, "40%");
		table.getCellFormatter().setWidth(0, 2, "15%");
		table.getCellFormatter().setWidth(0, 3, "15%");
		table.getCellFormatter().setWidth(0, 4, "15%");
		
		panel.add(navBar);
		table.getRowFormatter().setStyleName(0, "mail-ListHeader");

		// Initialize the rest of the rows.
		for (int i = 0; i < VISIBLE_EMAIL_COUNT; ++i) {
			table.setText(i + 1, 0, "");
			table.setText(i + 1, 1, "");
			table.setText(i + 1, 2, "");
			table.setText(i + 1, 3, "");
			table.setText(i + 1, 4, "");
			table.getCellFormatter().setWordWrap(i + 1, 0, false);
			table.getCellFormatter().setWordWrap(i + 1, 1, false);
			table.getCellFormatter().setWordWrap(i + 1, 2, false);
			table.getCellFormatter().setWordWrap(i + 1, 3, false);
			table.getCellFormatter().setWordWrap(i + 1, 4, false);
//			table.getFlexCellFormatter().setColSpan(i + 1, 2, 2);
		}
	}

	public void update() {

		// Show the selected emails.

		service.findGLByMonth("3", startIndex, VISIBLE_EMAIL_COUNT, new AsyncCallback() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				System.out.println(caught);
			}

			public void onSuccess(Object result) {
				// TODO Auto-generated method stub
				int i = 0;
				list= (List) result;
				for (Iterator it = list.iterator(); it.hasNext();) {
					final AccountCategory accountCategory = (AccountCategory) it
							.next();
					i++;
					// Add a new row to the table, then set each of its columns
					// to the
					// email's sender and subject values.
					table.setText(i + 1, 0, accountCategory.getAccountNumber());
					table.setText(i + 1, 1, accountCategory.getName());
					table.setText(i + 1, 2, accountCategory.getBalance()
							.toString());
					table.setText(i + 1, 3, accountCategory.getDebitTotal()==null?"0.0":accountCategory.getDebitTotal().toString());
					table.setText(i + 1, 4, accountCategory.getCreditTotal()==null?"0.0":accountCategory.getCreditTotal().toString());
				}

				// // Clear any remaining slots.
				// for (; i < VISIBLE_EMAIL_COUNT; ++i) {
				// table.setHTML(i + 1, 0, "&nbsp;");
				// table.setHTML(i + 1, 1, "&nbsp;");
				// table.setHTML(i + 1, 2, "&nbsp;");
				// }
				

			}

		});
		
		service.getGLCount(new AsyncCallback(){

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			public void onSuccess(Object result) {
				// TODO Auto-generated method stub
				count = ((Integer) result).intValue();
				setButton();
			}
			
		});

	}

	private void setButton(){
		newerButton.setVisible(startIndex != 0);
		olderButton.setVisible(startIndex + VISIBLE_EMAIL_COUNT < count);
		int max = startIndex + VISIBLE_EMAIL_COUNT;
		countLabel.setText("" + (startIndex + 1) + " - " + max + " of "
				+ count);
	}
	
	private void styleRow(int row, boolean selected) {
		if (row != -1) {
			if (selected) {
				table.getRowFormatter().addStyleName(row + 1,
						"mail-SelectedRow");
			} else {
				table.getRowFormatter().removeStyleName(row + 1,
						"mail-SelectedRow");
			}
		}
	}

	private void selectRow(int row) {
		// When a row (other than the first one, which is used as a header) is
		// selected, display its associated MailItem.
		//		  
		styleRow(selectedRow, false);
		styleRow(row, true);

		// item.read = true;
		selectedRow = row;
		// Mail.get().displayItem(item);
	}
	
	 private  class MyPopup extends PopupPanel {
		    public MyPopup(AccountCategory ac) {
		      super(true);
		      service.getGLItemById(ac.getAccountCategoryId(), new AsyncCallback<List<GLItem>>(){

				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					
				}

				public void onSuccess(List<GLItem> result) {
					// TODO Auto-generated method stub
					 
					  final FlexTable table = new FlexTable();
					  table.setText(0, 0, "Name");
						table.setText(0, 1, "Number");
						table.setText(0, 2, "Balance");
						table.setText(0, 3, "creditTotal");
						table.setText(0, 4, "debitTotal");
						int i =1;
						for(Iterator<GLItem> it = result.iterator();it.hasNext();){
							GLItem gl = it.next();
							table.setText(i, 0, gl.getName());
							table.setText(i, 1, gl.getNumber());
							table.setText(i, 2, gl.getBalanceAmount()==null?"":gl.getBalanceAmount().toString());
							table.setText(i, 3, gl.getCreditAmount()==null?"":gl.getCreditAmount().toString());
							table.setText(i, 4, gl.getDebitAmount()==null?"":gl.getDebitAmount().toString());
							i++;
						}
//					  table.setWidth("128px");
				      setWidget(table);
		
				      setStyleName("ks-popups-Popup");
				}
		    	  
		      });
		      
		    }
		  }
}
